//
//  ZKWKWebViewController.m
//  StudentKudou
//
//  Created by 赵坪生 on 2017/5/11.
//  Copyright © 2017年 赵坪生. All rights reserved.
//

#import "SUIWKWebViewController.h"
#import "SUIWKUserContentController.h"
#import "UIButton+EnlargeTouchArea.h"
//#import "ZKShareAdapter.h"

@interface SUIWKWebViewController ()<WKUIDelegate, WKNavigationDelegate>
@property(nonatomic, strong)WKWebView * webView;
@property(nonatomic, strong)UIProgressView *progressView;
@property(nonatomic, strong)UILabel * mytitleLabel;
@end

@implementation SUIWKWebViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (self.isHidenNaviBar) {
        self.navigationController.navigationBar.hidden = YES;
    }
    if (self.isMain) {
        self.navigationController.navigationBar.hidden = YES;
        self.navigationItem.hidesBackButton = NO;
        UIImage *aimage = [UIImage imageNamed:@"back_b"];
         UIImage *image = [aimage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setImage:image forState:UIControlStateNormal];
        /**
         *  设置frame只能控制按钮的大小
         */
        btn.frame= CGRectMake(0, 0, 20, 20);
        [btn addTarget:self action:@selector(onBack) forControlEvents:UIControlEventTouchUpInside];

        self.navigationItem.leftBarButtonItem =  [[UIBarButtonItem alloc] initWithCustomView:btn];
        UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
        negativeSpacer.width = -20;
        self.navigationItem.leftBarButtonItems = @[negativeSpacer,self.navigationItem.leftBarButtonItem];
    }
  
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if (self.isMain) {
        //获取状态栏的rect
        CGRect statusRect = [[UIApplication sharedApplication] statusBarFrame];
        //获取导航栏的rect
        CGRect navRect = self.navigationController.navigationBar.frame;
        CGFloat barH = statusRect.size.height+navRect.size.height;
        self.navigationController.navigationBar.hidden = YES;
        UIView* topImageView = [UIView new];
        [self.view addSubview:topImageView];
        [topImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.right.mas_equalTo(self.view).offset(0);
            make.height.mas_equalTo(barH);
        }];
        
        UILabel * Label = [UILabel new];
//        Label.text = @"这个发的方法";
        self.mytitleLabel = Label;
        Label.textColor = [UIColor blackColor];
        Label.font = [UIFont systemFontOfSize:17 weight:UIFontWeightRegular];
        [topImageView addSubview:Label];
        [Label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.mas_equalTo(topImageView.mas_bottom).offset(-7);
            make.centerX.mas_equalTo(topImageView.mas_centerX).offset(0);
            make.height.mas_equalTo(30);
        }];
        
        UIButton *qianbaoButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [qianbaoButton setImage:[UIImage imageNamed:@"back_b"] forState:UIControlStateNormal];
        [qianbaoButton setEnlargeEdgeWithTop:20 right:20 bottom:20 left:20];
        [topImageView addSubview:qianbaoButton];
        [qianbaoButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(topImageView.mas_left).offset(15);
            make.centerY.mas_equalTo(Label.mas_centerY).offset(0);
            make.height.mas_equalTo(20);
            make.width.mas_equalTo(20);
        }];
        [qianbaoButton bk_whenTapped:^{
            [self onBack];
        }];
        
        UIButton *qianbaoButton1 = [UIButton buttonWithType:UIButtonTypeCustom];
        [qianbaoButton1 setImage:[UIImage imageNamed:@"more_b"] forState:UIControlStateNormal];
        [qianbaoButton1 setEnlargeEdgeWithTop:20 right:20 bottom:20 left:20];
        [topImageView addSubview:qianbaoButton1];
        [qianbaoButton1 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(topImageView.mas_right).offset(-15);
            make.centerY.mas_equalTo(Label.mas_centerY).offset(0);
            make.height.mas_equalTo(20);
            make.width.mas_equalTo(20);
        }];
        [qianbaoButton1 bk_whenTapped:^{
//            [self onBack];
        }];

    }
    
    
    DEFINE_WEAK(self)
    WKWebViewConfiguration * configuration = [[WKWebViewConfiguration alloc] init];
    configuration.userContentController = [[SUIWKUserContentController alloc] initWithViewController:wself];
    self.webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:configuration];
    [self.view addSubview:self.webView];
    CGFloat height =0;
    if (self.isHidenNaviBar) {
        height = 0;
        self.dragView.hidden = NO;
    }
    if (self.isMain ) {
        CGRect statusRect = [[UIApplication sharedApplication] statusBarFrame];
        //获取导航栏的rect
        CGRect navRect = self.navigationController.navigationBar.frame;
        height = statusRect.size.height+navRect.size.height;
    }
    
    [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(wself.view.mas_top).offset(height);
        make.left.right.bottom.equalTo(wself.view);
    }];
    
    
    self.webView.UIDelegate = self;
    self.webView.navigationDelegate = self;
    assert(self.url || self.html);
    if (self.url) {
        NSURL * url = [NSURL URLWithString:self.url];
        [self.webView loadRequest:[[NSURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:30]];
    }else{
        NSString * resourcePath = [ [NSBundle mainBundle] resourcePath];
        [self.webView loadHTMLString:self.html baseURL:[NSURL fileURLWithPath:resourcePath]];
    }
    
    self.progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
    self.progressView.progressTintColor = [UIColor blueColor];
    [self.webView addSubview:self.progressView];
    [self.progressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(wself.webView);
        make.height.mas_equalTo(2);
    }];
    
    //监听estimatedProgress进度 ，原生title
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:NULL];
    [self.webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL];
//    [self.webView addObserver:self forKeyPath:@"URL" options:NSKeyValueObservingOptionNew context:nil];
    
//    self.dragView.backgroundColor = [UIColor redColor];
    [self.view bringSubviewToFront:self.dragView];
//    self.webView.scrollView.scrollEnabled = NO;
    
    if(self.isChat){
        UIView *bgview = [UIView new];
        bgview.backgroundColor = [UIColor clearColor];
        bgview.userInteractionEnabled = YES;
        [self.view addSubview:bgview];
        [bgview mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.top.equalTo(wself.view);
            make.height.mas_equalTo(120);
            make.width.mas_equalTo(100);
        }];
        [self.view bringSubviewToFront:bgview];
        [bgview bk_whenTapped:^{
            [[TIANAppDelegate shareAppDelegate] resetTab];
            [self dismissViewControllerAnimated:YES completion:^{
                [[TIANAppDelegate shareAppDelegate] resetTab];
            }];
        }];
    }
}

- (WKWebView *)getWkwebView{
    return self.webView;
}

- (void)share{
    NSDictionary *options = self.shareOptions();
    NSString *title = options[@"title"];
    NSString *descr = options[@"description"];
    NSString *iconURL = options[@"iconURL"];
    NSString *shareURL = nil;
    if (options[@"shareURL"]) {
        shareURL = options[@"shareURL"];
        shareURL = [shareURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    }else {
        shareURL = [self.url copy];
    }
    shareURL = [shareURL stringByAppendingString:[NSString stringWithFormat:@"&title=%@&img=%@",[title stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],iconURL]];
//    [ZKShareAdapter share:shareURL title:title description:descr thumbImage:iconURL platformType:(UMSocialPlatformType_UnKnown) success:^(BOOL isSuccess) {
//        [self userDid:RANK_SHARE];
//    }];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqualToString:@"URL"])
        {
            NSLog(@" 当前 URL------%@",self.webView.URL.absoluteString);
        }

    DEFINE_WEAK(self)
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        if (object == self.webView) {
            [self.progressView setAlpha:1.0f];
            [self.progressView setProgress:self.webView.estimatedProgress animated:YES];
            if(self.webView.estimatedProgress >= 1.0f) {
                [UIView animateWithDuration:0.3 delay:0.3 options:UIViewAnimationOptionCurveEaseOut animations:^{
                    [wself.progressView setAlpha:0.0f];
                } completion:^(BOOL finished) {
                    [wself.progressView setProgress:0.0f animated:NO];
                }];
            }
        }
        else{
//            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        }
    }
    else if ([keyPath isEqualToString:@"title"]){
        if (object == self.webView) {
//            if (![self.webView.title containsString:@"png"]) {
                self.navigationItem.title = self.webView.title;
            if (self.isMain) {
                self.mytitleLabel.text = self.webView.title;
            }
            NSLog(@"self.webView.title:%@",self.webView.title);
//            }
         
        }
        else{
//            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        }
    }
    else {
//        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}
- (void)webView:(WKWebView*)webView decidePolicyForNavigationAction:(WKNavigationAction*)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {

    if (navigationAction.navigationType == WKNavigationTypeLinkActivated) {
     NSURL *url = navigationAction.request.URL;
     [[UIApplication sharedApplication] openURL:url];
     decisionHandler(WKNavigationActionPolicyCancel);
     return;
    }
    decisionHandler(WKNavigationActionPolicyAllow);
}
-(void)onBack{
    if ([self.webView canGoBack]) {
        [self.webView goBack];
    }else{
//        [super onBack];
    }
}
-(WMDragView *)dragView{
    if (!_dragView) {
        @weakify(self)
           self.dragView = [[WMDragView alloc] initWithFrame:CGRectMake(kScreenWidth-80,kScreenHeight-TabbarHeight-NavigationbarHeight-100 , 80, 80)];
           self.dragView.freeRect = CGRectMake(0, 0, kScreenWidth, kScreenHeight-TabbarHeight);
//           self.dragView.backgroundColor = [UIColor redColor];
           self.dragView.dragEnable = YES;
           self.dragView.isKeepBounds = YES;
           self.dragView.hidden = YES;
           self.dragView.clipsToBounds = NO;
           [self.view addSubview:self.dragView];
        self.dragView.backgroundColor = [UIColor whiteColor];
//           self.dragView.clickDragViewBlock = ^(WMDragView *dragView) {
//               @strongify(self)
//               if ([self.webView canGoBack]) {
//                       [self.webView goBack];
//                   }
//           };
           [self.dragView.closeButton bk_whenTapped:^{
               @strongify(self)
               if ([self.webView canGoBack]) {
                       [self.webView goBack];
                   }
           }];
    }
    return _dragView;
}
-(void)dealloc{
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
    [self.webView removeObserver:self forKeyPath:@"title"];
    [[self.webView configuration].userContentController removeAllUserScripts];
}


- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:([UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }])];
    [self presentViewController:alertController animated:YES completion:nil];
}

// 确认框
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler{
//    kFunLog
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:([UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(NO);
    }])];
    [alertController addAction:([UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(YES);
    }])];
    [self presentViewController:alertController animated:YES completion:nil];
}

// 文本输入框
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable result))completionHandler{
//    kFunLog
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:prompt message:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.text = defaultText;
    }];
    [alertController addAction:([UIAlertAction actionWithTitle:@"完成" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(alertController.textFields[0].text?:@"");
    }])];

    [self presentViewController:alertController animated:YES completion:nil];
}
@end
